package com.cloudeasy.server.jwt;

import com.cloudeasy.server.po.UserInfo;
import com.cloudeasy.server.service.UserInfoService;
import com.cloudeasy.server.service.UserService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义Jwt密码增强
 */
@Component
@ConditionalOnMissingBean(name = "jwtTokenEnhancer")
public class CustomJwtTokenEnhancer implements TokenEnhancer {
    private final UserService userService;
    private final UserInfoService userInfoService;

    public CustomJwtTokenEnhancer(UserService userService, UserInfoService userInfoService) {
        this.userService = userService;
        this.userInfoService = userInfoService;
    }

    /**
     * 增强
     * 额外添加了用户是否具有管理员角色的状态
     *
     * @param accessToken    {@link OAuth2AccessToken}
     * @param authentication {@link OAuth2Authentication}
     * @return {@link OAuth2AccessToken}
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        User user = (User) authentication.getUserAuthentication().getPrincipal();
        String account = user.getUsername();
        Map<String, Object> info = new HashMap<>(16);
        String userId = userService.getByAccount(account).getId();
        info.put("userId", userId);
        info.put("account", account);
        UserInfo userInfo = userInfoService.getById(userId);
        info.put("nickname", userInfo.getNickname());
        info.put("lastLoginTime",userInfo.getLastLoginTime());
        info.put("sex", userInfo.getSex());
        info.put("avatar", userInfo.getAvatar());
        info.put("userAttentionCount", userInfo.getUserAttentionCount());
        info.put("fansCount", userInfo.getFansCount());
        info.put("description", userInfo.getDescription());
        info.put("hasAdminRole", userService.hasAdminRole(account));
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
